<template>
  <div>
    <el-form :inline="true" class="demo-form-inline" label-width="75px" label-position="right">
      <el-form-item label="系统名称：">
        <el-select :disabled="group !== 'tenancy'" size="small" v-model="searchData.system_id" placeholder="请选择"
          style="width:180px" clearable @change="systemIdChange">
          <el-option v-for="item in systemsLiteList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="匹配状态：">
        <el-select size="small" v-model="match_state1" placeholder="请选择" clearable style="width:200px">
          <el-option label="全部" :value="-2"></el-option>
          <el-option label="未摄片" :value="10"></el-option>
          <el-option label="未匹配" :value="0"></el-option>
          <el-option label="匹配成功" :value="1"></el-option>
          <el-option label="匹配失败" :value="-1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="检查时间：" label-width="75px">
        <div style="width: 225px">
          <SearchTime ref="searchTimeModel" :clearTime="clearTime" :disableTime="'after'" @getTimes="getTimes" />
        </div>
      </el-form-item>
      <el-form-item class="ml10">
        <el-button type="primary" size="small" @click="searchCondation">查询</el-button>
        <el-button type="primary" plain size="small" @click="resetCondation">重置</el-button>
      </el-form-item>
      <br>
      <el-form-item label="机构名称：" label-width="75px"> 
        <!-- group === 'dept' -->
        <el-select
          :disabled="institutionsLiteList.length === 0 || (group !== 'tenancy' && !ksyxlbPermission && jgyxlbPermission)"
          size="small" v-model="searchData.institution_id" placeholder="请选择" clearable style="width:180px"
          @change="institutionIdChange">
          <el-option v-for="item in institutionsLiteList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="来源机房：" label-width="75px">
        <el-select class="listRoomClass" :disabled="sourceObservationRooms.length === 0" size="small" multiple collapse-tags
          v-model="searchData.observationRooms" placeholder="请选择" clearable style="width:200px">
          <el-option v-for="item in sourceObservationRooms" :key="item.id" :label="item.room_name"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="检查类型：" label-width="75px">
        <el-select size="small" v-model="searchData.modalities_in_study" placeholder="请选择" style="width:100px" clearable>
          <el-option v-for="(item, index) in modalityTypeOptions" :value="item.value" :label="item.label"
            :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="keyValue" size="small" class="fl" style="width:100px">
          <el-option value="accession_number" label="检查编号"></el-option>
          <el-option value="patient_id" label="患者编号"></el-option>
          <el-option value="patient_name" label="患者姓名"></el-option>
        </el-select>
        <div class="fl" style="width: 212px">
          <el-input @keyup.enter.native="searchCondation" size="small" v-model="strValue" placeholder="检查编号、患者编号、患者姓名查询"
            clearable></el-input>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import SearchTime from "@/components/common/SearchTime"; // 搜索时间
import { mapGetters } from "vuex";

export default {
  data() {
    return {
      searchData: {
        system_id: "",
        institution_id: "",
        modalities_in_study: "",
        start_study_date_time: "",
        end_study_date_time: "",
        observationRooms: [],//来源机房---选中的

      },
      keyValue: "patient_name",
      strValue: "",
      modalityTypeOptions: [
        {
          value: "-1",
          label: "全部",
        },
        {
          value: "CT",
          label: "CT",
        },
        {
          value: "CR",
          label: "CR",
        },
        {
          value: "MR",
          label: "MR",
        },
        {
          value: "NM",
          label: "NM",
        },
        {
          value: "PT",
          label: "PT",
        },
        {
          value: "DX",
          label: "DX",
        },
        {
          value: "DR",
          label: "DR",
        },
        {
          value: "ES",
          label: "ES",
        },
        {
          value: "MG",
          label: "MG",
        },
        {
          value: "RF",
          label: "RF",
        },
        {
          value: "SC",
          label: "SC",
        },
        {
          value: "US",
          label: "US",
        },
        {
          value: "XA",
          label: "XA",
        },
        {
          value: "OT",
          label: "OT",
        },
        {
          value: "PET",
          label: "PET",
        },
        {
          value: "ECT",
          label: "ECT",
        },
        {
          value: "OP",
          label: "OP",
        },
        {
          value: "OPM",
          label: "OPM",
        },
        {
          value: "OPT",
          label: "OPT",
        },
        {
          value: "OPV",
          label: "OPV",
        },
        {
          value: "XC",
          label: "XC",
        },
        {
          value: "OIS",
          label: "OIS",
        }
      ], // 检查类型

      clearTime: false, // 清除查询时间
      initTime: [],
      institutionsLiteList: [], // 机构名称
      sourceObservationRooms: [],//来源机房---接口获取到的
      ksyxlbPermission: false,
      jgyxlbPermission: false,
    };
  },
  props: ["match_state", "systemsLiteList", "room_ids",'clear_select'],
  computed: {
    ...mapGetters(["group", "systemid", "deptInstitutionId"]),
    match_state1: {
      get() {
        return this.match_state;
      },
      set(val) {
        
        this.$emit("setMatchState", val);
      },
    },
  },
  watch: {
    'clear_select':{
      handler:function(newVal){
        if(newVal === true){
          console.log('匹配状态',this.match_state1);
          this.resetCondation()
        }

      },
      immediate: true,
    },
    // "searchData.system_id": {
    //   handler: function (newVal) {
    //     if (newVal) {
    //       this.institutionsLiteList = [];
    //       this.searchData.institution_id = "";
    //       this.getInstitutionsLiteList(newVal);
    //     }
    //   },
    //   immediate: true,
    // },
    // "searchData.institution_id": {
    //   handler: function (newVal) {
    //     console.log('有机构id',newVal);
    //     if (newVal) {
    //       this.institutionIdChange(newVal)
    //     }
    //   },
    //   immediate: true,
    // },
  },
  async mounted() {
    // 这里要改成 this.group
    const permissionArr = JSON.parse(sessionStorage.getItem('permissionArr')) || []
    this.jgyxlbPermission = permissionArr.some(o => o.code === 'ris_jgyxlb') // 机构
    this.ksyxlbPermission = permissionArr.some(o => o.code === 'ris_ksyxlb') // 系统
    // console.log('当前用户角色以及权限', this.group, this.jgyxlbPermission, this.ksyxlbPermission);
    if (this.group === "dept") {
      // 科室角色
      this.searchData.system_id = this.systemid;
      await this.getInstitutionsLiteList(this.searchData.system_id);
      // this.$nextTick(async () => {
        const setObj = JSON.parse(localStorage.getItem('setObj')) || JSON.parse(localStorage.getItem('setPacsObj')) || {}
        if (!this.ksyxlbPermission && this.jgyxlbPermission && setObj?.GeneralCliParameter_WorkInstitutionId) {
          this.searchData.institution_id = setObj.GeneralCliParameter_WorkInstitutionId

        } else {
          //默认选中机构id
          if ((this.ksyxlbPermission || this.jgyxlbPermission) && (this.deptInstitutionId || setObj?.GeneralCliParameter_WorkInstitutionId)) {
            if (setObj?.GeneralCliParameter_WorkInstitutionId) {
              this.searchData.institution_id = setObj.GeneralCliParameter_WorkInstitutionId
            }
            if (this.deptInstitutionId) {
              this.searchData.institution_id = this.deptInstitutionId
            }

          }

        }
        // console.log('数据不对哦', this.searchData.institution_id, this.room_ids);
        if (this.searchData.institution_id) {
          //有机构id 且 机房不为空
          this.sourceObservationRooms = [];
          this.searchData.observationRooms = [];
          await this.getObservationRoomsLiteList(this.searchData.institution_id)
            this.defaultSelectedRooms()
            // console.log('顺序1');
        }
      // })
    } else if (this.group === "doct") {
      this.searchData.system_id = this.systemid;
      await this.getInstitutionsLiteList(this.searchData.system_id);

      // this.$nextTick(async () => {
        this.searchData.institution_id = this.deptInstitutionId;
        if (this.searchData.institution_id) {
          //有机构id 且 机房不为空
          this.sourceObservationRooms = [];
          this.searchData.observationRooms = [];
          await this.getObservationRoomsLiteList(this.searchData.institution_id)
            this.defaultSelectedRooms()
        }
      // });
    }

    setTimeout(() => {
      // console.log('顺序2');

      if (this.$route.query?.beginData && this.$route.query?.endData) {
        let beginTime = this.$route.query.beginData.indexOf('00:00:00') !== -1 ? this.$route.query.beginData:`${this.$route.query.beginData} 00:00:00`
        let endTime = this.$route.query.endData.indexOf('23:59:59') !== -1 ? this.$route.query.endData:`${this.$route.query.beginData} 23:59:59`

        this.$refs.searchTimeModel.time = [beginTime,endTime]
        // [`${this.$route.query.beginData} 00:00:00`, `${this.$route.query.endData} 23:59:59`]
        this.getTimes(this.$refs.searchTimeModel.time)
      } else {
        // this.$refs.searchTimeModel.setDate();
        this.getTimes(this.$refs.searchTimeModel.time);
      }
    }, 100);
  },
  methods: {
    systemIdChange(val) {
      this.institutionsLiteList = [];
      this.sourceObservationRooms = [];
      this.searchData.observationRooms = [];
      this.searchData.institution_id = "";
      if (val) {
        this.getInstitutionsLiteList(val);
      }
      this.$emit('systemOrInstitutionChanged',this.searchData)
    },

    institutionIdChange(val) {
      // console.log('机构id为', val);
      this.sourceObservationRooms = [];
      this.searchData.observationRooms = [];
      if (val) {
        this.getObservationRoomsLiteList(val);
      }
      this.$emit('systemOrInstitutionChanged',this.searchData)

    },
    defaultSelectedRooms() {
    
      this.searchData.observationRooms = []
      let rooms = []
      this.room_ids.map(e => {
        let findItemIndex = this.sourceObservationRooms.findIndex(ele => e === ele.id)
        if (findItemIndex >= 0) {
          rooms.push(e)
        }
      })
      this.$nextTick(()=>{
        this.searchData.observationRooms = rooms
      })
    },
    getTimes(val) {
      this.clearTime = false

      this.searchData.start_study_date_time = val ? val[0] : "";
      this.searchData.end_study_date_time = val ? val[1] : "";
      this.searchCondation()
    },
    searchCondation() {
      // console.log('搜索参数s', this.searchData);
      // 搜索
      const searchData = {
        ...this.searchData,
        match_state: this.match_state,
        [this.keyValue]: this.strValue,
      };
      this.$emit("search", searchData);
    },
    //ksyx  科室影像  jgyx机构影像
    async resetCondation() {

      console.log('匹配状态',this.match_state1);

      // 重置
      const setObj = JSON.parse(localStorage.getItem('setObj')) || JSON.parse(localStorage.getItem('setPacsObj')) || {}
      if (this.group === "dept") {
        if (!this.ksyxlbPermission && this.jgyxlbPermission && setObj?.GeneralCliParameter_WorkInstitutionId) {
          this.searchData.institution_id = setObj.GeneralCliParameter_WorkInstitutionId

        } else {
          this.searchData.institution_id = "";
        }
      } else if (this.group === "tenancy") {
        this.searchData.system_id = "";
        this.searchData.institution_id = "";
      }
      this.keyValue = "patient_name";
      this.strValue = "";
      this.searchData.modalities_in_study = "";
      this.defaultSelectedRooms()

      if (this.searchData.institution_id) {
        //有机构id 且 机房不为空
        this.sourceObservationRooms = [];
        this.searchData.observationRooms = [];
        await this.getObservationRoomsLiteList(this.searchData.institution_id)
        this.$nextTick(() => {
          this.defaultSelectedRooms()
        })

      }
      // console.log('匹配状态',this.match_state1);

      if(this.clear_select){
        this.clearTime = true
        this.searchData.start_study_date_time = ''
        this.searchData.end_study_date_time = ''
        this.match_state1 = -1

        this.$emit('changeClear')
        const searchData = {
        ...this.searchData,
        match_state: this.match_state,
      };
      this.$emit("search", searchData);

      }else{
        this.match_state1 = "";

        setTimeout(() => {
        // this.$refs.searchTimeModel.setDate();
        this.getTimes(this.$refs.searchTimeModel.time);
      }, 100);
      }
      

      this.$emit("reset");


    },
    async getInstitutionsLiteList(val) {
      if (val) {

        let res = await this.$pacsApi.pacsApi.getInstitutionsLiteList({
          system_id: val,
        });
        let { code, data } = res;
        if (code === 0) {
          this.$nextTick(() => {
            this.institutionsLiteList = data;
          });
        }
      }
    },
    //来源机房
    async getObservationRoomsLiteList(val) {
      if (val) {
        let res = await this.$pacsApi.pacsApi.getObseRoom({ organizationId: val, SystemId: this.searchData.system_id })
        let { code, data } = res
        if (code === 0) {
          this.$nextTick(() => {
            this.sourceObservationRooms = data;
            this.defaultSelectedRooms()

          });
        }
      }
    },
  },
  components: {
    SearchTime,
  },
};
</script>
<style lang="less" scoped>
/deep/ .el-form-item__label {
  padding: 0px;
}

/deep/.el-form-item {
  margin-right: 5px;
}

/deep/ .el-input--suffix .el-input__inner {
  padding-right: 30px !important;
}
</style>
